
import { Cart } from '../cart/cart-model.js';
import { Order } from '../order/order-model.js';
import { Address } from '../../utils/address.js';

var cart = new Cart();
var order = new Order();
var address = new Address();


Page({
  data: {
    id: null,
  },
  onLoad: function (options) {
    var from = options.from;
    if(from=='cart'){
      this._fromCart(options.account);
    }else{
      this._fromOrder(options.id);
    }
  },

  // 从购物车跳转到订单
  _fromCart: function (account){
    var productsArr = cart.getCartDataFromLocal(true);
    var account = account;
    this.data.productsArr = productsArr;
    address.getAddress((res) => {
      this._bindAddressInfo(res);
    });
    this.setData({
      productsArr: productsArr,
      account: account,
      orderStatus: 0,
    });
  },

  // 从个人中心跳转到订单
  _fromOrder: function (id){
    // 如果返回orderid则显示订单信息
    if(id){
      var that = this;
      var id = id;
      // 通过order获取订单信息
      order.getOrderInfoByID(id, (data) => {
        that.setData({
          orderStatus: data.status,
          productsArr: data.snap_items,
          account: data.total_price,
          basicInfo: {
            orderTime: data.create_time,
            orderNo: data.order_no
          }
        });

        // 快照地址
        var addressInfo = data.snap_address;
        addressInfo.totalDetail = address.setAddressInfo(addressInfo);
        that._bindAddressInfo(addressInfo);
      });
    }
  },

  // 重置订单信息
  onShow: function() {
    if(this.data.id){
      this._fromOrder(this.data.id);
    }
  },
  // 更改收货地址
  editAddress:function(event){
    var that = this;
    wx.chooseAddress({
      success:function(res){
        var addressInfo = {
          name: res.userName,
          mobile: res.telNumber,
          totalDetail: address.setAddressInfo(res),
        }
        that._bindAddressInfo(addressInfo);

        // 保存地址
        address.submitAddress(res,(flag)=>{
          if(!flag){
            that.showTips('操作提示','地址信息更新失败');
          }
        });
      }
    })
  },
  // 绑定收货地址
  _bindAddressInfo: function (addressInfo){
    this.setData({
      addressInfo: addressInfo,
    });    
  },

  // 提示窗口
  showTips:function (title,content,flag){
    wx.showModal({
      title: title,
      content: content,
      showCancel: false,
      success: function(res){
        if(flag){
          wx.switchTab({
            url: '/pages/my/my',
          })
        }
      }
    });
  },

  // 支付操作
  pay:function(){
    // 检测用户是否填写收货地址
    if(!this.data.addressInfo){
      this.showTips('下单提示','请填写收货地址');
    }
    if(this.data.orderStatus == 0){
      // 首次下单创建订单
      this._firstTimePay();
    }else{
      // 直接支付
      this._oneMoresTimePay();
    }
  },

  /* 再次支付*/
  _oneMoresTimePay: function () {
    this._execPay(this.data.id);
  },

  // 首次下单
  _firstTimePay:function(){
    // 商品信息
    var orderInfo =[],
    order = new Order(),
    productInfo = this.data.productsArr;
    for (let i = 0; i < productInfo.length;i++){
      orderInfo.push({
        product_id: productInfo[i].id,
        count: productInfo[i].counts,
      });
    }
    var that = this;
    order.doOrder(orderInfo,(data)=>{
      if(data.pass){
        var id = data.order_id;
        that.data.id = id;
        that.data.fromCartFlag = false;
        // 开始支付
        that._execPay(id);
      }else{
        that._orderFail(data);
      }
    });
  },

  // 支付前操作
  _execPay: function (id) {
    var that = this;
    order.execPay(id,(statusCode)=>{
      if (statusCode != 0){
        // 将购物车中的商品删除
        that.deleteProducts();
        var flag = statusCode == 2;
        wx.navigateTo({
          url: '../pay-result/pay-result?id='+id+'&flag='+flag+'&from=order',
        })
      }
    });
  },

  // 删除购物车商品
  deleteProducts: function (){
    var ids = [], arr = this.data.productsArr;
    for (let i = 0; i < arr.length; i++) {
      ids.push(arr[i].id);
    }
    cart._deleteCartData(ids);
  },

  // 支付失败,没有库存
  _orderFail:function(data){
    var nameArr = [],
      name = '',
      str = '',
      pArr = data.productsArr;
    for (let i = 0; i < pArr.length; i++) {
      if (!pArr[i].haveStock) {
        name = pArr[i].name;
        if (name.length > 15) {
          name = name.substr(0, 12) + '...';
        }
        nameArr.push(name);
        if (nameArr.length >= 2) {
          break;
        }
      }
    }
    str += nameArr.join('、');
    if (nameArr.length > 2) {
      str += ' 等';
    }
    str += ' 缺货';
    wx.showModal({
      title: '下单失败',
      content: str,
      showCancel: false,
      success: function (res) {
      }
    });
  }

})